package com.coldwindblows.blog.controller.admin;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.dto.LogActions;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.UserDo;
import com.coldwindblows.blog.service.ILogService;
import com.coldwindblows.blog.service.IUserService;
import com.coldwindblows.blog.utils.PatternKit;
import com.coldwindblows.blog.utils.TaleUtils;

/**
 * 用户后台登录/退出
 * Created by ColdWindBlows on 2018/07/06
 */
@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = TipException.class)
@SuppressWarnings("rawtypes")
public class AuthController extends BaseController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ILogService logService;
	
	@GetMapping("/login")
	public String login() {
		return "admin/login";
	}
	
	@GetMapping("/register")
	public String register() {
		return "admin/register";
	}
	
	@PostMapping("/login")
	@ResponseBody
	public RestResponseBo dologin(String username, String password, String remeber_me, HttpServletRequest request, HttpServletResponse response) {
		Integer errorCount = cache.get("login_error_count");
		try {
			UserDo user = userService.login(username, password);
			request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
			if(StringUtils.isNotBlank(remeber_me)) {
				TaleUtils.setCookie(response, user.getUid());
			}
			logService.insertLog(LogActions.LOGIN.getAction(), null, request.getRemoteAddr(), user.getUid());
		} catch(Exception e) {
			errorCount = null == errorCount ? 1 : ++errorCount;
			if(errorCount > 3) {
				return RestResponseBo.fail("您输入密码错误超过3次，请10分钟后尝试");
			}
			cache.set("login_error_count", errorCount, 10 * 60);
			String msg = "登录失败";
			if(e instanceof TipException) {
				msg = e.getMessage();
			}
			return RestResponseBo.fail(msg);
		}
		
		return RestResponseBo.ok();
	}
	
	@PostMapping("/register")
	@ResponseBody
	public RestResponseBo doRegiest(String username, String password, String nickname, String email) {
		if(StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(email)) {
			return RestResponseBo.fail("请输入完整信息");
		}
		if(!PatternKit.isCharacter(username)) {
			return RestResponseBo.fail("请输入正确的用户名");
		}
		if(!PatternKit.isPassword(password)) {
			return RestResponseBo.fail("请输入正确的密码");
		}
		if(!PatternKit.isEmail(email)) {
			return RestResponseBo.fail("请输入正确的邮箱地址");
		}
		nickname = StringUtils.isBlank(nickname) ? username : nickname;
		userService.regiest(username, password, nickname, email);
		
		return RestResponseBo.ok();
	}
	
	@GetMapping("/logout")
	public String logout(HttpSession session, HttpServletResponse response) {
		session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
		Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
		cookie.setValue(null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
		
		return "redirect:login";
	}
}
